package environment.player;

import environment.Pitch;
import environment.Team;
import ain.*;
import ain.standard.StandardChaseAntibody;
import ain.standard.StandardGuardAntibody;
import ain.standard.StandardKickAntibody;
import ain.standard.StandardPassAntibody;
import ain.standard.StandardShootAntibody;
import ain.standard.StandardTrackAntibody;
import util.Vector;

public class StandardPlayer extends AbstractPlayer
{
	public StandardPlayer(Pitch pitch, Vector position, Team team)
	{
		super(pitch, position, team);
	}
	
	public void addImmuneNetwork()
	{
		antibodies.add(new StandardShootAntibody(this, pitch));
		antibodies.add(new StandardPassAntibody(this, pitch));
		antibodies.add(new StandardKickAntibody(this, pitch));
		antibodies.add(new StandardChaseAntibody(this, pitch));
		antibodies.add(new StandardTrackAntibody(this, pitch));
		antibodies.add(new StandardGuardAntibody(this, pitch));
		
		this.immuneNetwork = new ImmuneNetwork(antibodies);
	}
	
	public void kick(Vector impulse)
	{
		// add 20% noise to impulse
		Vector noise = new Vector(Math.random() * 2 - 1, Math.random() * 2 - 1);
		noise.normalize();
		noise.limit(impulse.magnitude() * 0.3);
		impulse.add(noise);
		
		// are we within kicking range?
		Vector distanceToBall = Vector.substract(pitch.getBall().getPosition(), position);
		if (distanceToBall.magnitude() > KICKING_RANGE)
		{
			walk(pitch.getBall().getPosition());
		}
		else
		{
			// can only shoot if ball is not moving
			if (pitch.getBall().getVelocity().magnitude() < 0.1)
			{
				long timeSinceLastKick = System.currentTimeMillis() - lastKickStartingTime;
				
				if (timeSinceLastKick > KICK_DURATION)
				{
					pitch.getBall().kick(impulse.limit(MAX_KICK_IMPULSE));
					lastKickStartingTime = System.currentTimeMillis();
				}
			}
		}
	}
	
	public void walk(Vector target)
	{
		// walks within half kickrange of target position
		
		// check if kicking movement is still in progress
		long timeSinceLastKick = System.currentTimeMillis() - lastKickStartingTime;
		if (timeSinceLastKick >= KICK_DURATION)
		{
			Vector distance = Vector.substract(target, position);
			// goal not yet reached?
			if (distance.magnitude() > KICKING_RANGE/2)
			{
				distance.limit(MAX_SPEED);
				velocity = distance;
				position.add(velocity);
			}
		}
	}
}
